package nil.ed.simulator.request.ui.jfx.component.qq;

import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.*;
import javafx.scene.web.WebView;
import nil.ed.simulator.request.enums.events.EventMode;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.bus.EventBus;
import nil.ed.simulator.request.guice.GuiceManager;
import nil.ed.simulator.request.ui.jfx.bean.qq.QQRow;
import nil.ed.simulator.request.ui.jfx.ui.table.TableCallback;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SuppressWarnings({"unchecked", "rawtypes"})
public class ExtendConfigTableCallback implements TableCallback {
    @Override
    public void accept(TableView<?> tableView) {
        TableColumn tableColumn = new TableColumn("操作");
        tableColumn.setCellValueFactory(f -> {
            QQRow qqRow = (QQRow) ((TableColumn.CellDataFeatures) f).getValue();
            if (QQRow.COOKIE_STATUS_NEED_VC.equals(qqRow.getCookieStatus())) {
                Button button = new Button("验证");
                button.setOnMouseClicked((e) -> {
                    showLoginDialog(qqRow);
                });
                return new SimpleObjectProperty<>(button);
            } else {
                return new SimpleStringProperty("无需操作");
            }
        });
        tableView.getColumns().add(tableColumn);
    }

    private void showLoginDialog(QQRow qqRow) {
        Dialog dialog = new Dialog();;
        WebView webView = new WebView();
        dialog.setGraphic(webView);
        webView.getEngine().load("https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=2001601&style=32&hide_border=0&hide_close_icon=1&hide_feedback=1&hide_reg=1&target=top&target=top&hide_title_bar=1&s_url=https://aq.qq.com/cn2/manage/mbtoken/app_index&lang=0&qlogin_jumpname=aqjump&qlogin_param=aqdest=https%3A//aq.qq.com/cn2/manage/mbtoken/app_index");
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
        dialog.setOnCloseRequest(ev -> {
            boolean loginSuccess = false;
            for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {
                if ("skey".equalsIgnoreCase(cookie.getName())) {
                    loginSuccess = true;
                    break;
                }
            }
            if (loginSuccess) {
                Map<String, Object> extendMap = new HashMap<>();
                extendMap.put("entity", qqRow.getQqItem());
                GuiceManager.INJECTOR.getInstance(EventBus.class).publish(Event.builder()
                        .source(null)
                        .eventMode(EventMode.SYNC)
                        .data(cookieManager.getCookieStore())
                        .extendMap(extendMap)
                        .eventType(EventType.COOKIE_STORE)
                        .build());

            } else {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("登录退出提醒");
                alert.setContentText(String.format("%s登录未完成!", qqRow.getQqItem().getQq()));
                alert.show();
            }
        });
        dialog.show();
        new Thread(() -> {
            try {
                while (webView.getEngine().getDocument() == null) {
                    TimeUnit.SECONDS.sleep(1);
                }
                Platform.runLater(() -> {
                    webView.getEngine().executeScript("document.getElementById('switcher_plogin').click();");
                    webView.getEngine().executeScript(String.format("document.getElementById('p').value = '%s';", qqRow.getQqItem().getPassword()));
                    webView.getEngine().executeScript(String.format("document.getElementById('u').value = '%s';", qqRow.getQqItem().getQq()));
                });
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }).start();

    }
}
